package com.aiti.lulian.pay.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.utils.message.Message;
import com.aiti.base.core.utils.stringUtil.StringUtil;
import com.aiti.lulian.entity.*;
import com.aiti.lulian.feign.CloudShowManagerSubService;
import com.aiti.lulian.mapper.CardVipInfoMapper;
import com.aiti.lulian.mapper.CardVipRecordMapper;
import com.aiti.lulian.pay.PayFactory;
import com.aiti.lulian.pay.PayStrategyContext;
import com.aiti.lulian.pay.dto.CardVipRecordDto;
import com.aiti.lulian.pay.enums.wxpay.OrderStatus;
import com.aiti.lulian.pay.model.AliPayPreOrderData;
import com.aiti.lulian.pay.model.CardVipInfo;
import com.aiti.lulian.pay.model.CardVipRecord;
import com.aiti.lulian.pay.model.PayInfo;
import com.aiti.lulian.pay.vo.CardVipRecordVo;
import com.aiti.lulian.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
@Slf4j
@RestController
@RequestMapping("/pay")
public class PayInfoController extends WebController {

    @Autowired
    private PayFactory payFactory;

    @Autowired
    private CardVipInfoMapper cardVipInfoMapper;

    @Autowired
    private CardVipRecordMapper cardVipRecordMapper;

    @Autowired
    private ILuLianEnterpriseService enterpriseService;

    @Autowired
    private ILulianEnterpriseHistoryService historyService;

    @Autowired
    private CloudShowManagerSubService managerSubService;

    @Autowired
    private ICardVipRecordService cardVipRecordService;

    @Autowired
    private CardVipRecordMapper vipRecordMapper;

    @Autowired
    private ILuLianEnterpriseExtensionService luLianEnterpriseExtensionService;

    @Autowired
    private IEnterpriseDictDataService enterpriseDictDataService;

    @Autowired
    private ISysDataService sysDataService;

    @GetMapping("/genToken")
    public Message genToken(@RequestParam("payType") String payType){
        String userId = findUserId();
        String token = payFactory.getToken(payType, userId);
        return Message.success(token);
    }

    @PostMapping("/genQrCode")
    public Message genQrCode(@Validated @RequestBody PayInfo payInfo){
        PayStrategyContext payStrategy = payFactory.getPayStrategy(payInfo.getPayType());
        if(StringUtils.isBlank(payInfo.getUserId())){
            payInfo.setUserId(findUserId());
        }

        //查询当前传入的餐套的金额和系统中的套餐的金额是不是一致的
        CardVipInfo cardVipInfo = cardVipInfoMapper.selectById(payInfo.getVipId());
        if(cardVipInfo == null){
            throw new RuntimeException("你传入的会员套餐不存在");
        }
        payInfo.setPayAmount(cardVipInfo.getVipAmount());
        payInfo.setVipName(cardVipInfo.getVipName());
        AliPayPreOrderData resultInfo = payStrategy.genQrCode(payInfo);
        return Message.success(resultInfo);
    }

    /***
     * 支付成功后支付宝回调的本地接口
     * @param params
     * @return 如果这里逻辑执行没有问题，这里必须返回 success
     */
    @PostMapping("/success")
    public String aliCallBack(@RequestParam Map<String,String> params){
        PayStrategyContext payStrategy = payFactory.getPayStrategy("1");
        return payStrategy.aliCallBack(params);
    }

    @GetMapping("/queryOrderStatus")
    public Message queryOrderStatus(@RequestParam("enterpriseId") String enterpriseId,
                                   @RequestParam("orderId") String orderId) throws Exception {
        String userId = findUserId();
        PayStrategyContext payStrategy = payFactory.getPayStrategy("1");
        String s = payStrategy.queryOrderStatus(orderId);
        if(StringUtil.equals(s,"success")){
            LuLianEnterprise enterprise = enterpriseService.getById(enterpriseId);
            CardVipRecord cardVipRecord = cardVipRecordMapper.selectById(orderId);
            if(enterprise == null){
                LuLianEnterpriseHistory history = historyService.getById(enterpriseId);
                LuLianEnterprise enterprise1 = new LuLianEnterprise();
                BeanUtil.copyProperties(history,enterprise1);
                enterprise1.setMiniProgramVersion(StringUtil.equals(cardVipRecord.getVipLevel(),"基础版") ? 1 : 2);
                Date currentDate = new Date();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(currentDate);
                calendar.add(Calendar.YEAR, 1);
                Date dateAfterOneYear = calendar.getTime();
                enterprise1.setExpireTime(dateAfterOneYear);
                enterprise1.setPayChannel(2);
                enterpriseService.save(enterprise1);
            }else{
                Date currentDate = new Date();
                Integer purchaseMiniProgramVersion =  StringUtil.equals(cardVipRecord.getVipLevel(),"基础版") ? 1 : 2;
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(currentDate);
                calendar.add(Calendar.YEAR, 1);
                Date dateAfterOneYear = calendar.getTime();
                enterprise.setExpireTime(dateAfterOneYear);
                enterprise.setPayChannel(2);
                enterprise.setMiniProgramVersion(purchaseMiniProgramVersion);
                enterpriseService.updateById(enterprise);
            }
            LuLianEnterpriseExtension extension = luLianEnterpriseExtensionService.getOne(new LambdaQueryWrapper<LuLianEnterpriseExtension>().eq(LuLianEnterpriseExtension::getEnterpriseId, enterpriseId));
            if (extension == null) {
                LuLianEnterpriseExtension build = LuLianEnterpriseExtension.builder().enterpriseId(enterpriseId).build();
                luLianEnterpriseExtensionService.save(build);
            }
            if (! StringUtil.equals(cardVipRecord.getVipLevel(), "基础版")) {
                List<EnterpriseDictData> enterpriseDictDataList = enterpriseDictDataService.list(new LambdaQueryWrapper<EnterpriseDictData>().eq(EnterpriseDictData::getEnterpriseId, enterpriseId));
                if (enterpriseDictDataList.size() == 0) {
                    List<SysData> cardCustomerTypeList = sysDataService.list(new LambdaQueryWrapper<SysData>().eq(SysData::getDictTypeNo, "CARD_CUSTOMER_TYPE")
                            .orderByAsc(SysData::getBaseId));
                    List<SysData> cardCustomerSourceList = sysDataService.list(new LambdaQueryWrapper<SysData>().eq(SysData::getDictTypeNo, "CARD_CUSTOMER_SOURCE")
                            .orderByAsc(SysData::getBaseId));
                    List<SysData> cardCustomerFollowStatusList = sysDataService.list(new LambdaQueryWrapper<SysData>().eq(SysData::getDictTypeNo, "CARD_CUSTOMER_FOLLOW_STATUS")
                            .orderByAsc(SysData::getBaseId));
                    int i = 0;
                    int j = 0;
                    int k = 0;
                    List<EnterpriseDictData> dataList = new ArrayList<>();
                    //默认的客户类型
                    for (SysData cardCustomerType : cardCustomerTypeList) {
                        EnterpriseDictData cardCustomerTypeDictData = EnterpriseDictData.builder().dictTypeNo(cardCustomerType.getDictTypeNo()).dictTypeName("客户类型").baseName(cardCustomerType.getBaseName()).typeId(cardCustomerType.getTypeId())
                                .sort(i ++).isUpdated(StrUtil.equals(cardCustomerType.getBaseId(), "7ee01fe48a2647eb8b549acd28c45899") ? "0" : "1").module("8725839a-1488-4c30-9ef4-6d7369e28f00,8725839a-1488-4c30-9ef4-6d7369e28f01")
                                .enterpriseId(enterpriseId).creator("1").baseCreateTime(new Date()).build();
                        dataList.add(cardCustomerTypeDictData);
                    }
                    //默认的客户来源
                    for (SysData cardCustomerSource : cardCustomerSourceList) {
                        EnterpriseDictData cardCustomerSourceDictData = EnterpriseDictData.builder().dictTypeNo(cardCustomerSource.getDictTypeNo()).dictTypeName("客户来源").baseName(cardCustomerSource.getBaseName()).typeId(cardCustomerSource.getTypeId())
                                .sort(j ++).isUpdated("1").module("8725839a-1488-4c30-9ef4-6d7369e28f00,8725839a-1488-4c30-9ef4-6d7369e28f01")
                                .enterpriseId(enterpriseId).creator("1").baseCreateTime(new Date()).build();
                        dataList.add(cardCustomerSourceDictData);
                    }
                    //默认的跟进状态
                    for (SysData cardCustomerFollowStatus : cardCustomerFollowStatusList) {
                        EnterpriseDictData cardCustomerFollowStatusDictData = EnterpriseDictData.builder().dictTypeNo(cardCustomerFollowStatus.getDictTypeNo()).dictTypeName("跟进状态").baseName(cardCustomerFollowStatus.getBaseName()).typeId(cardCustomerFollowStatus.getTypeId())
                                .sort(k ++).isUpdated((StrUtil.equals(cardCustomerFollowStatus.getBaseId(), "c661b397f83a4fd590f3c79ac4040dad1") || StrUtil.equals(cardCustomerFollowStatus.getBaseId(), "c661b397f83a4fd590f3c79ac4040dad4")) ? "0" : "1").module("8725839a-1488-4c30-9ef4-6d7369e28f00,8725839a-1488-4c30-9ef4-6d7369e28f01,8725839a-1488-4c30-9ef4-6d7369e28f03,8725839a-1488-4c30-9ef4-6d7369e28f04")
                                .enterpriseId(enterpriseId).creator("1").baseCreateTime(new Date()).build();
                        dataList.add(cardCustomerFollowStatusDictData);
                    }
                    enterpriseDictDataService.saveBatch(dataList);
                }
            }

            CardVipRecord cardVipRecord1 = new CardVipRecord();
            cardVipRecord1.setBaseId(orderId);
            cardVipRecord1.setOrderStatus("1");
            cardVipRecordMapper.updateById(cardVipRecord1);

            Map<String,String> map = new HashMap<>();
            map.put("userId",userId);
            map.put("roleId","043ea2e3e02c4aa591df1f83e65069bc");
//            managerSubService.addUserRole(map);
            int countUserRoleCount = vipRecordMapper.selectUserRole(userId,"043ea2e3e02c4aa591df1f83e65069bc");
            if(countUserRoleCount <= 0){
                vipRecordMapper.insertUserRole(IdUtil.simpleUUID(),userId,"043ea2e3e02c4aa591df1f83e65069bc");
            }

            return Message.success("订单成功支付");
        }else if(StringUtil.equals(s,"wait") || StringUtil.equals(s,"notfound")){
            return Message.fail("订单还在等待支付中，请及时支付");
        }else{
            return Message.fail("订单查询失败");
        }
    }

    @ApiOperation("微信支付通知")
    @PostMapping("/native/notify")
    public String nativeNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        PayStrategyContext payStrategy = payFactory.getPayStrategy("2");
        return payStrategy.callBack(request, response);


    }

    @GetMapping("/queryWxOrderStatus")
    public Message queryWxOrderStatus(@RequestParam("enterpriseId") String enterpriseId,
                                    @RequestParam("orderId") String orderId) throws Exception {
        String userId = findUserId();
        PayStrategyContext payStrategy = payFactory.getPayStrategy("2");
        String s = payStrategy.queryOrderStatus(orderId);
        log.info("查询微信支付状态");

        if(OrderStatus.SUCCESS.name().equals(s)){//支付成功
            LuLianEnterprise enterprise = enterpriseService.getById(enterpriseId);
            CardVipRecord cardVipRecord = cardVipRecordMapper.selectById(orderId);
            if(enterprise == null){
                LuLianEnterpriseHistory history = historyService.getById(enterpriseId);
                LuLianEnterprise enterprise1 = new LuLianEnterprise();
                BeanUtil.copyProperties(history,enterprise1);
                enterprise1.setMiniProgramVersion(StringUtil.equals(cardVipRecord.getVipLevel(),"基础版") ? 1 : 2);
                Date currentDate = new Date();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(currentDate);
                calendar.add(Calendar.YEAR, 1);
                Date dateAfterOneYear = calendar.getTime();
                enterprise1.setExpireTime(dateAfterOneYear);
                enterprise1.setPayChannel(1);
                enterpriseService.save(enterprise1);
            }else{
                Date currentDate = new Date();
                Integer purchaseMiniProgramVersion =  StringUtil.equals(cardVipRecord.getVipLevel(),"基础版") ? 1 : 2;
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(currentDate);
                calendar.add(Calendar.YEAR, 1);
                Date dateAfterOneYear = calendar.getTime();
                enterprise.setExpireTime(dateAfterOneYear);
                enterprise.setPayChannel(1);
                enterprise.setMiniProgramVersion(purchaseMiniProgramVersion);
                enterpriseService.updateById(enterprise);
            }
            LuLianEnterpriseExtension extension = luLianEnterpriseExtensionService.getOne(new LambdaQueryWrapper<LuLianEnterpriseExtension>().eq(LuLianEnterpriseExtension::getEnterpriseId, enterpriseId));
            if (extension == null) {
                LuLianEnterpriseExtension build = LuLianEnterpriseExtension.builder().enterpriseId(enterpriseId).build();
                luLianEnterpriseExtensionService.save(build);
            }
            if (! StringUtil.equals(cardVipRecord.getVipLevel(), "基础版")) {
                List<EnterpriseDictData> enterpriseDictDataList = enterpriseDictDataService.list(new LambdaQueryWrapper<EnterpriseDictData>().eq(EnterpriseDictData::getEnterpriseId, enterpriseId));
                if (enterpriseDictDataList.size() == 0) {
                    List<SysData> cardCustomerTypeList = sysDataService.list(new LambdaQueryWrapper<SysData>().eq(SysData::getDictTypeNo, "CARD_CUSTOMER_TYPE")
                            .orderByAsc(SysData::getBaseId));
                    List<SysData> cardCustomerSourceList = sysDataService.list(new LambdaQueryWrapper<SysData>().eq(SysData::getDictTypeNo, "CARD_CUSTOMER_SOURCE")
                            .orderByAsc(SysData::getBaseId));
                    List<SysData> cardCustomerFollowStatusList = sysDataService.list(new LambdaQueryWrapper<SysData>().eq(SysData::getDictTypeNo, "CARD_CUSTOMER_FOLLOW_STATUS")
                            .orderByAsc(SysData::getBaseId));
                    int i = 0;
                    int j = 0;
                    int k = 0;
                    List<EnterpriseDictData> dataList = new ArrayList<>();
                    //默认的客户类型
                    for (SysData cardCustomerType : cardCustomerTypeList) {
                        EnterpriseDictData cardCustomerTypeDictData = EnterpriseDictData.builder().dictTypeNo(cardCustomerType.getDictTypeNo()).dictTypeName("客户类型").baseName(cardCustomerType.getBaseName()).typeId(cardCustomerType.getTypeId())
                                .sort(i ++).isUpdated(StrUtil.equals(cardCustomerType.getBaseId(), "7ee01fe48a2647eb8b549acd28c45899") ? "0" : "1").module("8725839a-1488-4c30-9ef4-6d7369e28f00,8725839a-1488-4c30-9ef4-6d7369e28f01")
                                .enterpriseId(enterpriseId).creator("1").baseCreateTime(new Date()).build();
                        dataList.add(cardCustomerTypeDictData);
                    }
                    //默认的客户来源
                    for (SysData cardCustomerSource : cardCustomerSourceList) {
                        EnterpriseDictData cardCustomerSourceDictData = EnterpriseDictData.builder().dictTypeNo(cardCustomerSource.getDictTypeNo()).dictTypeName("客户来源").baseName(cardCustomerSource.getBaseName()).typeId(cardCustomerSource.getTypeId())
                                .sort(j ++).isUpdated("1").module("8725839a-1488-4c30-9ef4-6d7369e28f00,8725839a-1488-4c30-9ef4-6d7369e28f01")
                                .enterpriseId(enterpriseId).creator("1").baseCreateTime(new Date()).build();
                        dataList.add(cardCustomerSourceDictData);
                    }
                    //默认的跟进状态
                    for (SysData cardCustomerFollowStatus : cardCustomerFollowStatusList) {
                        EnterpriseDictData cardCustomerFollowStatusDictData = EnterpriseDictData.builder().dictTypeNo(cardCustomerFollowStatus.getDictTypeNo()).dictTypeName("跟进状态").baseName(cardCustomerFollowStatus.getBaseName()).typeId(cardCustomerFollowStatus.getTypeId())
                                .sort(k ++).isUpdated((StrUtil.equals(cardCustomerFollowStatus.getBaseId(), "c661b397f83a4fd590f3c79ac4040dad1") || StrUtil.equals(cardCustomerFollowStatus.getBaseId(), "c661b397f83a4fd590f3c79ac4040dad4")) ? "0" : "1").module("8725839a-1488-4c30-9ef4-6d7369e28f00,8725839a-1488-4c30-9ef4-6d7369e28f01,8725839a-1488-4c30-9ef4-6d7369e28f03,8725839a-1488-4c30-9ef4-6d7369e28f04")
                                .enterpriseId(enterpriseId).creator("1").baseCreateTime(new Date()).build();
                        dataList.add(cardCustomerFollowStatusDictData);
                    }
                    enterpriseDictDataService.saveBatch(dataList);
                }
            }

            Map<String,String> map = new HashMap<>();
            map.put("userId",userId);
            map.put("roleId","043ea2e3e02c4aa591df1f83e65069bc");
//            managerSubService.addUserRole(map);

            int countUserRoleCount = vipRecordMapper.selectUserRole(userId,"043ea2e3e02c4aa591df1f83e65069bc");
            if(countUserRoleCount <= 0){
                vipRecordMapper.insertUserRole(IdUtil.simpleUUID(),userId,"043ea2e3e02c4aa591df1f83e65069bc");
            }

            return Message.success("订单成功支付");
        }else if(OrderStatus.NOTPAY.name().equals(s)){
            return Message.fail("订单还在等待支付中，请及时支付");
        }else{
            return Message.fail("订单查询失败");
        }
    }

    @GetMapping("/purchasInfo")
    public Message purchasInfo(@RequestParam("enterpriseId") String enterpriseId) {
        LuLianEnterprise enterprise = enterpriseService.getById(enterpriseId);
        Map map = new HashMap();
        if(enterprise == null){
            map.put("basicFlag",false);
            map.put("superFlag",false);
        }else{
            Date expireTime = enterprise.getExpireTime();
            Integer payChannel = enterprise.getPayChannel();
            Integer miniProgramVersion = enterprise.getMiniProgramVersion();
            if(miniProgramVersion == null){
                map.put("basicFlag",false);
                map.put("superFlag",false);
            }else{
                //目前免费使用的企业
                if(expireTime == null){
                    if(miniProgramVersion == 1){
                        map.put("basicFlag",true);
                        map.put("superFlag",false);
                    }else if(miniProgramVersion == 2){
                        map.put("basicFlag",true);
                        map.put("superFlag",true);
                    }

                }else{
                    if(expireTime.before(new Date())){//过期
                        map.put("basicFlag",false);
                        map.put("superFlag",false);
                    }else{//没过期
                        if(miniProgramVersion == 1){
                            map.put("basicFlag",true);
                            map.put("superFlag",false);
                        }else if(miniProgramVersion == 2){
                            map.put("basicFlag",true);
                            map.put("superFlag",true);
                        }
                    }

                }

            }

        }

        return Message.success(map);
    }

    @ApiOperation("对公转账 - 获取企业的确认码")
    @GetMapping("/public/transfer/confirmationCode")
    private synchronized Message getConfirmationCode(@RequestParam("enterpriseId") String enterpriseId) {
        String userId = findUserId();
//        String userId = "1";
        if (StrUtil.isBlank(userId)) {
            return Fail("请先登录");
        }
        return cardVipRecordService.getConfirmationCode(enterpriseId);
    }

    @ApiOperation("对公转账 - 确认已转账")
    @PostMapping("/public/transfer/confirm")
    public synchronized Message confirm(@RequestBody CardVipRecordDto cardVipRecordDto){
        String userId = findUserId();
//        String userId = "1";
        if (StrUtil.isBlank(userId)) {
            return Fail("请先登录");
        }
        cardVipRecordDto.setUserId(userId);
        return cardVipRecordService.confirm(cardVipRecordDto);
    }

    @ApiOperation("对公转账 - 查询列表")
    @GetMapping("/public/transfer/list")
    public synchronized Message getList(CardVipRecordDto cardVipRecordDto){
//        String userId = findUserId();
        String userId = "1";
        if (StrUtil.isBlank(userId)) {
            return Fail("请先登录");
        }
        Integer pageNum = cardVipRecordDto.getPageNum();
        Integer pageSize = cardVipRecordDto.getPageSize();
        Page<CardVipRecord> page = startPage(pageNum, pageSize);
        List<CardVipRecordVo> resultList = cardVipRecordService.getList(cardVipRecordDto, page);
        return Success(getPageResult(resultList, pageNum, pageSize, page.getTotal()));
    }

    @ApiOperation("对公转账 - 开通")
    @PutMapping("/public/transfer/open")
    public synchronized Message open(@RequestBody CardVipRecordDto cardVipRecordDto){
//        String userId = findUserId();
        String userId = "1";
        if (StrUtil.isBlank(userId)) {
            return Fail("请先登录");
        }
        return cardVipRecordService.open(cardVipRecordDto);
    }
}